import pygame
import random
import math

pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Xia Men Parker Tree New Bee")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
font = pygame.font.Font("msyh.ttf", 36)
START = 0
PLAYING = 1
PAUSED = 2
GAME_OVER = 3
NEXT_LEVEL = 4
state = START
keys = {'left': pygame.K_a, 'right': pygame.K_d, 'fire': pygame.K_SPACE}
player_pos = [400, 550]
player_size = 50
player_speed = 5
player_bullets = []
player_lives = 5
bullet_count = 0
last_fire_time = 0
flash_duration = 3000
is_flashing = False
flash_start_time = 0
enemies = []
enemy_size = 40
max_enemies = 50
enemy_bullets = []
enemy_move_interval = 5000
last_enemy_move_time = 0
bullet_speed = 10
max_player_bullets = 50
max_enemy_bullets = 10
start_time = 0
elapsed_time = 0

def draw_text(text, pos, color=WHITE):
    text_surface = font.render(text, True, color)
    text_rect = text_surface.get_rect(center=pos)
    screen.blit(text_surface, text_rect)

def format_time(seconds):
    minutes = seconds // 60
    seconds %= 60
    hours = minutes // 60
    minutes %= 60
    return f"{hours:02}:{minutes:02}:{seconds:02}"

def create_enemy(x, y):
    enemy_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    num_sides = 9
    angle = 360 / num_sides
    points = [(x + enemy_size * 0.5 * math.cos(math.radians(i * angle)), y + enemy_size * 0.5 * math.sin(math.radians(i * angle))) for i in range(num_sides)]
    return {'points': points, 'color': enemy_color, 'hit': 0}

def initialize_enemies():
    global enemies
    enemies = []
    columns = 10
    rows = 5
    spacing_x = (800 - (columns * enemy_size)) // (columns + 1)
    spacing_y = (200 - (rows * enemy_size)) // (rows + 1)
    for row in range(rows):
        for col in range(columns):
            enemy_x = spacing_x * (col + 1) + col * enemy_size + enemy_size // 2
            enemy_y = spacing_y * (row + 1) + row * enemy_size + enemy_size // 2
            enemies.append(create_enemy(enemy_x, enemy_y))

def start_screen():
    global state, start_time, elapsed_time
    draw_text("按回车开始", (400, 300))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
            state = PLAYING
            clear_game()
            start_time = pygame.time.get_ticks()
            elapsed_time = 0

def pause_game():
    global state
    draw_text("暂停", (400, 300))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
            state = PLAYING

def game_over():
    global state
    draw_text("游戏结束", (400, 300))
    draw_text(f"累计时间: {format_time(elapsed_time)}", (400, 350))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
            state = START
            clear_game()

def next_level():
    global state
    draw_text("恭喜，进入下一关", (400, 300))
    draw_text(f"累计时间: {format_time(elapsed_time)}", (400, 350))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
            state = PLAYING
            clear_game()

def clear_game():
    global player_bullets, enemies, enemy_bullets, player_lives, last_fire_time, is_flashing, flash_start_time, last_enemy_move_time, start_time, elapsed_time
    player_bullets.clear()
    enemies.clear()
    enemy_bullets.clear()
    player_lives = 5
    last_fire_time = 0
    is_flashing = False
    flash_start_time = 0
    last_enemy_move_time = pygame.time.get_ticks()
    initialize_enemies()

def add_enemies():
    while len(enemies) < 50 and len(enemies) < max_enemies:
        new_enemy = create_enemy(random.randint(0, 800 - enemy_size), random.randint(-100, -enemy_size))
        enemies.append(new_enemy)

running = True
while running:
    screen.fill(BLACK)
    if state == START:
        start_screen()
    elif state == PLAYING:
        current_time = pygame.time.get_ticks()
        elapsed_time = (current_time - start_time) // 1000
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    state = PAUSED
                if event.key == keys['fire']:
                    if bullet_count < max_player_bullets:
                        player_bullets.append([player_pos[0] + player_size // 2, player_pos[1]])
                        bullet_count += 1
                        last_fire_time = current_time
                        is_flashing = True
                        flash_start_time = current_time
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[keys['left']]:
            player_pos[0] -= player_speed
        if keys_pressed[keys['right']]:
            player_pos[0] += player_speed
        player_pos[0] = max(0, min(800 - player_size, player_pos[0]))
        if is_flashing and current_time - flash_start_time < flash_duration:
            if (current_time - flash_start_time) % 200 < 100:
                pygame.draw.rect(screen, GREEN, (*player_pos, player_size, player_size))
        else:
            is_flashing = False
            pygame.draw.rect(screen, GREEN, (*player_pos, player_size, player_size))
        for bullet in player_bullets:
            bullet[1] -= bullet_speed
            pygame.draw.circle(screen, RED, (int(bullet[0]), int(bullet[1])), 5)
            if bullet[1] < 0:
                player_bullets.remove(bullet)
        if current_time - last_enemy_move_time >= enemy_move_interval:
            for enemy in enemies:
                enemy['points'] = [(x, y + enemy_size) for x, y in enemy['points']]
            last_enemy_move_time = current_time
        for enemy in enemies:
            if len(enemy['points']) >= 3:
                pygame.draw.polygon(screen, enemy['color'], enemy['points'])
            if len(enemy_bullets) < max_enemy_bullets and random.random() < 0.01:
                enemy_bullets.append([enemy['points'][0][0] + enemy_size // 2, enemy['points'][0][1] + enemy_size])
            if any(y + enemy_size >= player_pos[1] for x, y in enemy['points']):
                state = GAME_OVER
        for bullet in enemy_bullets:
            bullet[1] += bullet_speed
            pygame.draw.circle(screen, RED, (int(bullet[0]), int(bullet[1])), 5)
            if bullet[1] > 600:
                enemy_bullets.remove(bullet)
        for bullet in player_bullets[:]:
            for enemy in enemies[:]:
                if any(bullet[0] >= x and bullet[0] <= x + enemy_size and bullet[1] >= y and bullet[1] <= y + enemy_size for x, y in enemy['points']):
                    enemies.remove(enemy)
                    player_bullets.remove(bullet)
                    break
        for bullet in enemy_bullets[:]:
            if (player_pos[0] <= bullet[0] <= player_pos[0] + player_size and
                player_pos[1] <= bullet[1] <= player_pos[1] + player_size):
                player_lives -= 1
                enemy_bullets.remove(bullet)
                if player_lives <= 0:
                    state = GAME_OVER
        if len(enemies) < 50:
            add_enemies()
        if not enemies:
            state = NEXT_LEVEL
        draw_text(format_time(elapsed_time), (50, 550))
    elif state == PAUSED:
        pause_game()
    elif state == GAME_OVER:
        game_over()
    elif state == NEXT_LEVEL:
        next_level()
    pygame.display.flip()
    pygame.time.Clock().tick(60)

pygame.quit()